﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace WirelessAccessPoint.Interactivity
{
    /// <summary>
    /// PasswordBoxがLostFocusする際に入力文字をトリムするビヘイビアです。
    /// 
    /// 【使用方法】
    /// <i:Interaction.Behaviors>
    ///     <behavior:TrimPasswordBoxBehavior TrimMode="Both" />
    /// </i:Interaction.Behaviors>
    /// </summary>
    public class TrimPasswordBoxBehavior : Behavior<PasswordBox>
    {
        public static readonly DependencyProperty TrimModeProperty = DependencyProperty.Register(
            "TrimMode",
            typeof(TrimMode),
            typeof(TrimPasswordBoxBehavior),
            new FrameworkPropertyMetadata(TrimMode.Both));

        public TrimMode TrimMode
        {
            get { return (TrimMode) this.GetValue(TrimModeProperty); }
            set { this.SetValue(TrimModeProperty, value); }
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.LostKeyboardFocus += this.LostKeyboardFocus;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.LostKeyboardFocus -= this.LostKeyboardFocus;
        }

        private void LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            var associatedObject = sender as PasswordBox;

            if (associatedObject.Password != null)
            {
                switch (this.TrimMode)
                {
                    case TrimMode.Both:
                        associatedObject.Password = associatedObject.Password.Trim();
                        break;

                    case TrimMode.Start:
                        associatedObject.Password = associatedObject.Password.TrimStart();
                        break;

                    case TrimMode.End:
                        associatedObject.Password = associatedObject.Password.TrimEnd();
                        break;
                }
            }
        }
    }
}
